<template>
  <div class="article-page">

    <div class="banner">
      <div class="container">

        <h1>{{ article.title }}</h1>

        <!-- TODO: 完善收藏用户功能 -->
        <article-meta :article="article"
                      :isAuthor="article.author.username === user.username"
                      @favorite="favorite"
                      @follow="follow"
                      @delete="deleteArticle" />

      </div>
    </div>

    <div class="container page">

      <div class="row article-content">
        <div class="col-md-12"
             v-html="article.body"></div>
      </div>

      <hr />

      <div class="article-actions">
        <article-meta :article="article"
                      :isAuthor="article.author.username === user.username"
                      @favorite="favorite"
                      @follow="follow"
                      @delete="deleteArticle" />
      </div>

      <div class="row">
        <!-- TODO: 提取留言板作为一个小模块（已完成） -->
        <comment-board :user="user"
                       :comments="comments"
                       @publishComment="publish"
                       @deleteComment="deleteComment"
                       ref="commentBoard" />

      </div>

    </div>

  </div>
</template>

<script>
import { mapState } from 'vuex'
import articleMeta from '@/components/articleMeta'
import commentBoard from '@/components/commentBoard'
import MarkdownIt from 'markdown-it'
import {
  getArticle,
  getComments,
  favoriteArticle,
  unfavoriteArticle,
  publishComment,
  deleteComment,
  deleteArticle
} from '@/api/article'
import {
  followUser,
  unfollowUser
} from '@/api/user'

export default {
  name: 'Article',
  components: {
    articleMeta,
    commentBoard
  },
  head() {
    return {
      title: `${this.article.title} - ${this.article.author.username} (realworld)`,
      meta: [
        {
          hid: 'description', //
          name: 'description',
          content: this.article.description // 内容
        }
      ]
    }
  },
  async asyncData({ params, redirect }) {
    let article, comments
    try {
      let [{
        data: articleData
      }, {
        data: commentData
      }] = await Promise.all([
        getArticle(params.slug),
        getComments(params.slug)
      ])
      article = articleData.article
      comments = commentData.comments
    } catch (e) {
      redirect('/')
    }

    // let { article } = data
    let md = new MarkdownIt()
    article.body = md.render(article.body)
    article.favoriteDisable = false
    article.author.followDisable = false
    return {
      article,
      comments
    }
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    async favorite(article) {
      article.favoriteDisable = true
      if (article.favorited) {
        // 已赞，取消赞
        let result = await unfavoriteArticle(article.slug)
        console.log(result)
        article.favorited = false
        article.favoritesCount -= 1
      } else {
        // 点赞
        await favoriteArticle(article.slug)
        article.favorited = true
        article.favoritesCount += 1
      }
      article.favoriteDisable = false
    },
    async follow(author) {
      author.followDisable = true
      if (author.following) {
        await unfollowUser(author.username)
        author.following = false
      } else {
        await followUser(author.username)
        author.following = true
      }
      author.followDisable = false
    },
    async publish(comment) {
      let result = await publishComment(this.article.slug, {
        comment: {
          body: comment
        }
      })
      if (result.status === 200) {
        this.comments.unshift(result.data.comment)
        this.$refs.commentBoard.cleanComment()
      }
    },
    async deleteComment(comment) {
      let result = await deleteComment(this.article.slug, comment.id)
      if (result.status === 200) {
        let idx = this.comments.findIndex(c => c.id === comment.id)
        if (idx >= 0) {
          this.comments.splice(idx, 1)
        }
      }
    },
    async deleteArticle(slug) {
      let result = await deleteArticle(slug)
      console.log(result)
      if (result.status === 200) {
        this.$router.replace('/')
      }
    }
  }
}
</script>

<style>
</style>